<template>
  <div>
    <Layout>
      <template #search>
        <el-form
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          :v-show="true"
          label-width="68px"
        >
          <el-form-item label="上传时间" prop="uploadTime">
            <el-date-picker
              v-model="queryParams.uploadTime"
              type="date"
              :disabled-date="disabledDate"
              :shortcuts="shortcuts"
              format="YYYY/MM/DD"
              placeholder="Pick a day"
              value-format="YYYY-MM-DD HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              :disabled="multiple"
              @click="handleExport"
              >导出
            </el-button>
          </el-col>
        </el-row>
      </template>

      <template #content>
        <el-table :data="tableList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            prop="id"
            label="上传记录编号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="userId"
            label="用户编号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="materialId"
            label="素材编号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="uploadTime"
            label="上传时间"
            align="center"
          ></el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                >修改
              </el-button>
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getPageList"
        />
        <!-- 添加或修改对话框 -->
        <Dialog
          :show="dialogConfig.show"
          :title="dialogConfig.title"
          :buttons="dialogConfig.buttons"
          width="600px"
          :showCancel="false"
          @close="clear"
          :showClose="false"
          :closeOnClickModal="true"
        >
          <el-form
            ref="dialogQueryFormRef"
            :model="form"
            :rules="rules"
            label-width="80px"
            inline
          >
            <el-form-item label="上传记录编号" prop="id">
              <el-input
                v-model="form.id"
                placeholder="请输入上传记录编号"
                style="width: 200px; height: 32px"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="用户编号" prop="userId">
              <el-input
                v-model="form.userId"
                placeholder="请输入用户编号"
                style="width: 200px; height: 32px"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="素材编号" prop="materialId">
              <el-input
                v-model="form.materialId"
                placeholder="请输入素材编号"
                style="width: 200px; height: 32px"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="上传时间" prop="uploadTime">
              <el-input
                v-model="form.uploadTime"
                placeholder="请输入上传时间"
                style="width: 200px; height: 32px"
                clearable
              ></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </Dialog>
      </template>
    </Layout>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  getCurrentInstance,
  nextTick,
  computed,
  onMounted,
  provide,
  toRefs,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Layout from "@/components/Layout/Layout-common.vue";
import {
  getUploadHistoryList,
  getUploadHistoryById,
  addUploadHistory,
  updateUploadHistory,
  deleteUploadHistory,
  deleteUploadHistoryBatch,
} from "@/api/uploadHistory.js";
import { download } from "@/utils/request.js";
import { deleteOssFile } from "@/api/page/home.js";
import Dialog from "@/components/Dialog.vue";

// 分页数据
const total = ref(0);
// 用户数据
const tableList = ref([]);
// 用户选择项
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);

// 定义 queryFormRef
const queryFormRef = ref(null);
// 搜索查询数据
const queryData = reactive({
  // 搜索栏的数据
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  // 搜索栏的表单校验规则
  queryRules: {},
});
// 搜索-禁止超过当前时间
const disabledDate = (time) => {
  return time.getTime() > Date.now();
};
const { queryParams, queryRules } = toRefs(queryData);

// 弹窗的表单数据
const formData = reactive({
  // 修改、新增弹窗表单数据
  form: {},
  rules: {},
  // 需要删除的文件数组（删除之前存储的文件）
  imgData: [],
});
// 修改、新增弹窗表单数据
const dialogQueryFormRef = ref();
// 上传组件的ref
const uploadRef = ref();
// 结构属性，转为ref
const { form, rules, imgData } = toRefs(formData);

// 弹窗相关参数
const dialogConfig = reactive({
  show: false,
  title: "",
  buttons: [
    {
      type: "primary",
      text: "确定",
      click: (e) => {
        submitForm();
      },
    },
  ],
});

// 搜索-时间-快捷选择
const shortcuts = [
  {
    text: "今天",
    value: new Date(),
  },
  {
    text: "昨天",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      return date;
    },
  },
  {
    text: "一周前",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
      return date;
    },
  },
];

onMounted(() => {
  getPageList();
});

// 搜索栏的查询
const handleQuery = () => {
  getPageList();
};

// 重置查询条件
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
  };
};

// 批量操作
const handleSelectionChange = (val) => {
  ids.value = val.map((item) => item.id);
  single.value = val.length != 1;
  multiple.value = !val.length;
  console.log("ids:", ids.value);
};

// 导出数据
const handleExport = () => {
  // 发送请求
  download(
    "/UploadHistory/export",
    ids.value,
    `上传记录_${new Date().getTime()}.xlsx`
  );
};

// 获取所有数据
function getPageList() {
  getUploadHistoryList(queryParams.value).then((response) => {
    tableList.value = response.rows;
    console.log("tableList:", tableList.value);
    total.value = response.total;
  });
}

// 弹窗表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    materialId: null,
    uploadTime: null,
  };
}

/** 新增按钮操作 */
function handleAdd() {
  dialogConfig.show = true;
  dialogConfig.title = "添加上传记录";
  reset();
}

// 修改按钮操作
function handleUpdate(row) {
  const id = row.id || ids.value;
  getUploadHistoryById(id).then((response) => {
    form.value = response.data;
    //
    dialogConfig.show = true;
    dialogConfig.title = "修改上传记录";
  });
}

//  删除按钮操作
const handleDelete = (row) => {
  // 判断参数ids是否有值
  // 有,则执行删除多个操作
  if (ids.value.length > 0) {
    ElMessageBox.confirm("是否确认删除", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(function () {
      deleteUploadHistoryBatch(ids.value)
        .then((result) => {
          if (result.code == 200) {
            ElMessage.success("删除成功");
          }
          if (result.code == 500) {
            ElMessage.error("删除失败");
          }
        })
        .catch((err) => {
          ElMessage.error("删除失败");
        });
      // 重新获取数据
      setTimeout(() => {
        getPageList();
      }, 200);
    });
  }
  if (ids.value.length == 0) {
    ElMessageBox.confirm("是否确认删除", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(function () {
      console.log("row:", row);
      // 删除操作
      deleteUploadHistory(row.id)
        .then((result) => {
          if (result.code == 200) {
            ElMessage.success("删除成功");
          }
          if (result.code == 500) {
            ElMessage.error("删除失败");
          }
        })
        .catch((err) => {
          ElMessage.error("删除失败");
        });
      // 重新获取数据
      setTimeout(() => {
        getPageList();
      }, 200);
    });
  }
};

// 弹框确认  修改/添加
const submitForm = () => {
  // 修改操作
  if (dialogConfig.title == "修改上传记录") {
    // console.log("修改操作", form.value);
    // 上传新的图片，获取数据
    updateUploadHistory(form.value)
      .then((result) => {
        if (result.code == 200) {
          ElMessage.success("修改成功");
        }
      })
      .catch((err) => {
        ElMessage.error("修改失败");
      });
  }

  // 添加操作
  else if (dialogConfig.title == "添加上传记录") {
    // console.log("添加操作", form.value);
    // 校验表单参数，是否填写
    form.value.delFlag = 0;
    addUploadHistory(form.value)
      .then((result) => {
        if (result.code == 200) {
          ElMessage.success("添加成功");
        }
        if (result.code == 500) {
          // ElMessage.error("添加失败");
          // 向后端发起请求，删除刚才上传的文件
        }
      })
      .catch((err) => {});
  }
  // 判断ImgData是否有值，有则
  if (imgData.value.length) {
    console.log("删除方法执行了吗！");
    // 向后端发起请求，删除旧文件
    deleteOssFile(imgData.value);
  }

  // 重新获取数据
  setTimeout(() => {
    getPageList();
  }, 100);
  dialogConfig.show = false;
};

// 数据还原
const clear = () => {
  // 清除上传子组件的文件列表和img
  imgData.value = [];
  dialogConfig.show = false;
  setTimeout(() => {
    reset();
  }, 200);
};

// 弹窗表单上传组件功能
const getFilePath = (filePath) => {
  // 上传文件之前，把前一个文件路径，记录下来
  // 获取文件名 保存之前的文件的路径，便于删除
  let fileName = form.value.imgUrl?.split("/").pop() || "";
  imgData.value.push(fileName);
  //   修改form的属性值
  form.value.coverImg = filePath;
};
</script>

<style lang="scss" scoped></style>
